#!/usr/bin/env python
# -*- coding: utf-8 -*-

# Predesys - Predesys Bluetooth Proxy
# Version: 0.1.1
# Author: Jose A. Jimenez <jajimc@gmail.com>
# License: GPL 3.0 (see "license" file)

import sys
import os.path
sys.dont_write_bytecode = True
import xml.dom.minidom
import exceptions

class SimpleXmlDocument():
    """Class for parse a simple XML document. It only provides access to text nodes values."""
    def __init__(self, path):
        """Class constructor.
        
        Keyword arguments:
        path -- XML file path (string)
        
        It raises an exception (FileNotFoundException) if path doesn't exist.
        """
        if not (os.path.exists(path) and os.path.isfile(path)):
            raise FileNotFoundException("Configuration file not found.")
            
        try:
            self.document = xml.dom.minidom.parse(path)
        except:
            raise ParseXmlException("Error parsing configuration file.")
    
    def get_text_node_value(self, tagName, index):
        """Returns the value of a text node.
    
        Keyword arguments:
        tagName -- Node tag name (string)
        index -- Index of the node array asociated to tagName (integer)
        
        It raises an exception (ParseXmlException) if tagName or index are not valid.
        """
        try:
            text = str(self.__get_text(document.getElementsByTagName(tagName)[index].childNodes))
        except:
            raise ParseXmlException("Node tag name or node index not valid.")
        return text
        
    def __get_text(self, nodeList):    
        """Given a text node, it returns its value.
        
        Keyword arguments:
        nodeList -- The text node
        
        """
        text = []
        for node in nodeList:
            if node.nodeType == node.TEXT_NODE:
                text.append(node.data)
        return "".join(text)
        
class FileNotFoundException(exceptions.Exception):
    pass
    
class ParseXmlException(exceptions.Exception):
    pass
